<template>
  <BaseContainer>
    <QueryFilter :model="queryFields" @submit="handleQueryData" @reset="resetQueryData">
      <a-form-item name="libId" label="词库名称">
        <lib-searcher
          v-model:lib-id="queryFields.libId"
          :searching="queryLibLoading"
          :options="libWithQuery.wordLibs"
          @on-search="handleLibQuery"
        />
      </a-form-item>
      <a-form-item name="word" label="禁售词">
        <a-input placeholder="请输入禁售词" v-model:value.trim="queryFields.word" allow-clear />
      </a-form-item>
      <a-form-item name="industryId" label="行业">
        <industry-cascader :industry-list="industryList" v-model:industry-id="queryFields.industryId" />
      </a-form-item>
    </QueryFilter>
    <Divider />
    <table-toolbar title="禁售词列表">
      <a-button type="primary" @click="handleCreate">
        <template #icon><plus-outlined /></template>
        添加禁售词
      </a-button>
    </table-toolbar>
    <a-table
      row-key="id"
      :loading="loading"
      :pagination="pagination"
      :columns="columns"
      :data-source="bannedWordList?.words ?? []"
      @change="handleTableChange"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'operate'">
          <a-popconfirm title="确定要删除吗？" @confirm="handleRemove(record)">
            <a-button danger>删除</a-button>
          </a-popconfirm>
        </template>
      </template>
    </a-table>
    <banned-word-updater
      v-model:data="formFields"
      v-model:show="dialog.show"
      :industry-list="industryList"
      :mode="dialog.mode"
      :searching="libLoading"
      :submitting="submitting"
      :lib-list="libList.wordLibs"
      @on-submit="handleSubmit"
      @on-search="handleLibSearch"
    />
  </BaseContainer>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue'
import TableToolbar from '@/components/table-toolbar/index.vue'
import { PatternEnum, PatternKeyMap } from '@/views/word-lib/interface'
import type { TableProps } from 'ant-design-vue'
import { message } from 'ant-design-vue'
import getBannedWord, { type BannedWord } from '@/services/banned-word/getBannedWord'
import BannedWordUpdater from '@/views/word-lib/components/BannedWordUpdater.vue'
import updateDict, { type DictFields } from '@/services/dict-management/updateDict'
import removeDict from '@/services/dict-management/removeDict'
import getIndustryList from '@/services/order/getIndustryList'
import IndustryCascader from '@/components/industry-cascader/index.vue'
import getWordLib from '@/services/word-lib/getWordLib'
import LibSearcher from '@/views/word-lib/components/LibSearcher.vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import BaseContainer from '@/components/base-container/index.vue'
import QueryFilter from '@/components/query-filter/index.vue'
import Divider from '@/components/divider/index.vue'
import { Mode } from '@/core/interfaces/common'

const defaultFormFields = () => ({
  id: undefined,
  libId: undefined,
  libName: '',
  industryId: undefined,
  industryName: '',
  matchStyle: undefined,
  word: ''
})

const defaultQueryFields = () => ({
  industryId: undefined,
  libId: undefined,
  word: ''
})

const queryFields = reactive(defaultQueryFields())
const formFields = ref<Partial<DictFields>>(defaultFormFields())

const dialog = reactive({
  mode: Mode.create,
  show: false
})

const pagination = reactive({
  current: 1,
  pageSize: 15,
  total: 0
})

const columns: TableProps['columns'] = [
  {
    title: '禁售词名称',
    dataIndex: 'word',
    key: 'word',
    width: '150px'
  },
  {
    title: '词库名称',
    dataIndex: 'libName',
    key: 'libName',
    width: '150px'
  },
  {
    title: '匹配方式',
    dataIndex: 'matchStyle',
    key: 'matchStyle',
    customRender: ({ text }: { text: PatternEnum }) => {
      return PatternKeyMap[text]
    }
  },
  {
    title: '行业名称',
    dataIndex: 'industryName',
    key: 'industryName'
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime'
  },
  {
    title: '创建人',
    dataIndex: 'creator',
    key: 'creator'
  },
  {
    title: '操作',
    dataIndex: 'operate',
    key: 'operate',
    width: '100px'
  }
]

const [libWithQuery, queryLibList, queryLibLoading] = getWordLib()
const [libList, fetchLibList, libLoading] = getWordLib()
const [industryList, fetchIndustryList] = getIndustryList()
const [bannedWordList, fetchBannedWord, loading] = getBannedWord()
const [, submitDict, submitting] = updateDict()
const [, deleteDict] = removeDict()

async function loadBannedWord() {
  const [err, res] = await fetchBannedWord({
    ...queryFields,
    industryId: queryFields?.industryId || 0,
    libId: queryFields?.libId || 0,
    pageSize: pagination.pageSize,
    pageNum: pagination.current
  })

  if (!err) {
    pagination.total = res.data.data.totalSize
  }
}

function handleLibSearch(libName: string = '') {
  fetchLibList({
    name: libName,
    matchStyle: PatternEnum.ALL,
    pageNum: 1,
    pageSize: 20
  })
}

function handleLibQuery(libName: string = '') {
  queryLibList({
    name: libName,
    matchStyle: PatternEnum.ALL,
    pageNum: 1,
    pageSize: 20
  })
}

async function handleSubmit() {
  const [err, res] = await submitDict(formFields.value)

  if (!err) {
    dialog.show = false
    await handleQueryData()
  }
}

function handleTableChange(pag: { pageSize: number; current: number }) {
  pagination.pageSize = pag.pageSize
  pagination.current = pag.current
  loadBannedWord()
}

function handleQueryData() {
  pagination.pageSize = 15
  pagination.current = 1
  loadBannedWord()
}

function resetQueryData() {
  Object.assign(queryFields, defaultQueryFields())
  pagination.pageSize = 15
  pagination.current = 1
  loadBannedWord()
}

function handleCreate() {
  dialog.show = true
  dialog.mode = Mode.create
  formFields.value = defaultFormFields()
}

async function handleRemove(record: BannedWord) {
  const [err, res] = await deleteDict({
    id: record.id
  })

  if (!err) {
    message.success(res.data.msg || '删除成功')
    await loadBannedWord()
  } else {
    message.error(err.message || '删除失败，请稍候再试...')
  }
}

onMounted(() => {
  loadBannedWord()
  fetchIndustryList()
  handleLibSearch()
  handleLibQuery()
})
</script>

<script lang="ts">
export default {
  name: 'BannedWord'
}
</script>
